import {Component, OnInit} from '@angular/core';
import {NgForm} from "@angular/forms";
import {HttpClient, HttpHeaders} from "@angular/common/http";
import {Router} from "@angular/router";
import {Result} from "../result";

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  constructor(
    private http: HttpClient,
    private router: Router
  ) {
  }

  ngOnInit(): void {
  }


  onSubmit(f: NgForm) {
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/x-www-form-urlencoded'
      })
    };

    const username = f.value.username;
    const password = f.value.password;
    const params = "username=" + username + "&password=" + password;

    this.http.post<Result>('api/login', params, httpOptions)
      .subscribe((result) => {
          if (result.message === "登陆成功")
            this.router.navigateByUrl('user')
              .then(() => console.log("登录成功"))
          else
            console.log("验证失败")
        }
      );

  }

}
